package externalBusiness;

import com.alibaba.fastjson.JSONObject;
import models.MyConfig;
import models.MySleep;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;

/**
 * Created by yangxianming on 2018/12/14.
 * ArrayList 来循环处理发来的操作请求
 *
 *
 */
public class No2Factory extends Thread{
    private ArrayList<JSONObject> taskList = new ArrayList<JSONObject>();
    private MyConfig myConfig;

    public void setMyConfig(MyConfig myConfig) {
        this.myConfig = myConfig;
    }

    public void inputFactory(JSONObject jo){
        this.taskList.add(jo);
    }

    public int getListSize(){
        return taskList.size();
    }

    @Override
    public void run() {
        String pythonPath = myConfig.getPythonPath();
        String pythonCommand = myConfig.getPropertiesConfig().getProperties().getProperty("pythonCommand");
        while (true){
            MySleep.sleep(1000);
            if (taskList.size() <= 0){
                myConfig.setNo2Factory(null);
                break;
            }

            //把data数组传给ActionScheduler做处理
            System.out.println("taskList size:" + taskList.size());
            try {
                String caseName = taskList.get(0).getString("caseName");
                String caseId = taskList.get(0).getString("caseId");
                String batchNo = taskList.get(0).getString("batchNo");

                //普通环境下的py启动命令
                String command = pythonCommand + " " + pythonPath + " " + caseName + " " + caseId + " " + batchNo;
                System.out.println(command);
                Process process = Runtime.getRuntime().exec(command);

                //正确的流
                Reader reader = new InputStreamReader(process.getInputStream(), Charset.forName("GBK"));
                BufferedReader bf = new BufferedReader(reader);
                String wellReturn = "";
                String line;
                while ((line = bf.readLine()) != null){
                    wellReturn = wellReturn + line;
                }
                System.out.println("SUCCESS info: " + wellReturn);

                //错误的流
                reader = new InputStreamReader(process.getErrorStream(), Charset.forName("GBK"));
                bf = new BufferedReader(reader);
                String errReturn = "";
                while ((line = bf.readLine()) != null){
                    errReturn = errReturn + line;
                }
                System.out.println("ERROR info: " + errReturn);

            }catch (Exception e){
                e.printStackTrace();
            }
            taskList.remove(0);
        }
    }
}